package com.java.controller;

import com.java.entity.vo.WeChatTokenResponse;
import com.java.service.WeChatTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/wechat")
public class WeChatTokenController {

    @Autowired
    private WeChatTokenService weChatTokenService;

    /**
     * 获取AccessToken
     * @param appid appid
     * @param secret secret
     * @return
     */
    @GetMapping("/token")
    public String getToken(
            @RequestParam("appid") String appid,
            @RequestParam("secret") String secret) {

        WeChatTokenResponse response = weChatTokenService.getAccessToken(appid, secret);

        // 可以根据微信返回结果进行一次包裹处理
        if (response.getErrcode() != null && response.getErrcode() != 0) {

            // 这里选择直接返回，并标记错误
            response.setAccess_token(null); // 保证有错误时 access_token 为空
        }
        return response.getAccess_token();
    }
}